package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Borrow;
import com.itheima.pojo.User;
import com.itheima.service.BookBorrowService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@RestController
@RequestMapping("/bookborrow")
public class BookBorrowController {
    @Reference
    private BookBorrowService borrowService;
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = borrowService.pageQuery(queryPageBean);
        return pageResult;
    }
    //分页查询
    @RequestMapping("/borrow")
    public Result Borrow(@RequestBody Borrow borrow){
        String book_id2 = borrow.getBook_id();
        Integer book_id = Integer.parseInt(book_id2);
        String loan_card_id = borrow.getLoan_card_id();
        User user = borrowService.findByLoan(loan_card_id);
        if(user.getBorrowed_number()>=user.getMax_number()){
            return new Result(false,"读者正在借阅的书数量已满");
        }else {
            try {
                Date date = new Date();
                Calendar calendar = new GregorianCalendar();
                calendar.add(Calendar.DATE,5);
                calendar.setTime(date);
                borrow.setBorrow_time(date);
                borrow.setEnd_time(calendar.getTime());
                borrowService.borrow(borrow);
                borrowService.borrowsearch(book_id);
                borrowService.borrowuser(user.getBorrowed_number()+1,loan_card_id);
                return new Result(true,"借阅成功");
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,"借阅失败");
            }
        }
    }

}
